<template>
  <div>
    <el-card style="margin:20px 0px">
      <CategorySelect @getCategoryId="getCategoryId" :show="!isShowTable">
        <CategorySelect />
      </categoryselect>
    </el-card>
    <el-card>
      <div v-show="isShowTable">
        <el-button :disabled="category3Id?false:true" type="primary" size="mini" icon="el-icon-plus" @click="addAttr">
          添加属性
        </el-button>
        <!-- 表格:展示平台属性 -->
        <el-table :data="attrList" style="width: 100%" border>
          <el-table-column type="index" label="序号" width="80" align="center" />
          <el-table-column prop="attrName" label="属性名称" width="150" />
          <el-table-column prop="prop" label="属性值列表" width="width">
            <template slot-scope="{row}">
              <el-tag v-for="attrValue in row.attrValueList" :key="attrValue.id" style="margin:0 5px" type="success">{{ attrValue.valueName }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="prop" label="操作" width="150">
            <template slot-scope="{row}">
              <el-button type="warning" icon="el-icon-edit" size="mini" @click="updataAttr(row)" />
              <el-button type="danger" icon="el-icon-delete" size="mini" />
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 添加属性|修改属性 -->
      <div v-show="!isShowTable">
        <el-form ref="form" :inline="true" label-width="80px" :model="attrInfo">
          <el-form-item label="属性名">
            <el-input v-model="attrInfo.attrName" placeholder="请输入属性名" />
          </el-form-item>
          <el-button :disabled="attrInfo.attrName?false:true" type="primary" icon="el-icon-plus" @click="addAttrValue">添加属性值</el-button>
          <el-button @click="isShowTable=true">取消</el-button>
          <el-table :data="attrInfo.attrValueList" border style="width: 100%;margin:20px 0px">
            <el-table-column align="center" type="index" label="序号" width="80" />
            <el-table-column prop="prop" label="属性值名称" width="width">
              <template slot-scope="{row,$index}">
                <!-- 这里结构需要用到span与input来回切换 -->
                <el-input v-if="row.flag" :ref="$index" v-model="row.valueName" size="mini" placeholder="请输入属性值" @keyup.native.enter="row.flag=false" @blur="toLook(row)" />
                <span v-else style="display:block" @click="toEdit(row,$index)">{{ row.valueName }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="prop" label="操作" width="width">
              <template slot-scope="{row,$index}">
                <el-popconfirm :title="`确定删除'${row.valueName}'吗？`" @onConfirm="deleteAttrValue($index)">
                  <el-button slot="reference" type="danger" size="mini" icon="el-icon-delete" />
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
          <el-button :disabled="attrInfo.attrValueList.length<1" type="primary" @click="addOrUpdataAttr">保存</el-button>
          <el-button @click="isShowTable=true">取消</el-button>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script>
// 按需引入lodash中的深拷贝
import cloneDeep from 'lodash/cloneDeep'
export default {
  name: 'Attr',
  data() {
    return {
      category1Id: '',
      category2Id: '',
      category3Id: '',
      attrList: [],
      // 控制table表格显示与隐藏
      isShowTable: true,
      // 收集新增属性|修改属性使用的
      attrInfo: {
        attrName: '', // 属性名
        attrValueList: [],
        categoryId: 0, // 三级分类id
        categoryLevel: 3 // 三级分类id
      }
      // 属性值编辑区
    }
  },
  methods: {
    // 自定义事件回调
    getCategoryId({ categoryId, level }) {
      // 区分三级分类ID,以及父组件进行存储
      if (level === 1) {
        this.category1Id = categoryId
        this.category2Id = ''
        this.category3Id = ''
      } else if (level === 2) {
        this.category2Id = categoryId
        this.category3Id = ''
      } else {
        this.category3Id = categoryId
        // 当拿到三级分类ID就发送请求获取数据
        this.getAttrList()
      }
    },
    // 获取平台属性数据
    async getAttrList() {
      const { category1Id, category2Id, category3Id } = this
      const res = await this.$API.attr.reqAttrList(category1Id, category2Id, category3Id)
      if (res.code === 200) {
        this.attrList = res.data
      }
    },
    // 添加属性
    addAttrValue() {
      // 向属性值的数组里面添加元素
      this.attrInfo.attrValueList.push({
        attrId: undefined,
        valueName: '',
        flag: true
      })
      this.$nextTick(() => {
        this.$refs[this.attrInfo.attrValueList.length - 1].focus()
      })
    },
    // 添加属性值按钮的回调
    addAttr() {
      this.isShowTable = false
      this.attrInfo = {
        attrName: '', // 属性名
        attrValueList: [],
        categoryId: this.category3Id, // 三级分类id
        categoryLevel: 3 // 三级分类id
      }
    },
    // 修改属性
    updataAttr(row) {
      this.isShowTable = false

      this.attrInfo = cloneDeep(row)
      // 在修改属性值的时候,在相应的属性值上添加flag
      this.attrInfo.attrValueList.forEach(item => {
        this.$set(item, 'flag', false)
      })
    },
    // 失去焦点,切换为查看模式,展示span
    toLook(row) {
      // 属性值不能为空  不能重复
      if (row.valueName.trim() === '') {
        this.$message.error('属性值不能为空')
        return
      }
      // 新增属性值 不能与已有属性值重复
      const isRepat = this.attrInfo.attrValueList.some(item => {
        // 判断的时候需要将row从数组里面去出
        if (row !== item) {
          return row.valueName === item.valueName
        }
      })
      if (isRepat) {
        this.$message.error('属性值不能重复')
        return
      }
      row.flag = false
    },
    // 点击span的回调,变为编辑模式
    toEdit(row, index) {
      row.flag = true
      // 获取input节点,实现自动聚焦
      // 当节点渲染完毕会执行一次
      this.$nextTick(() => {
        this.$refs[index].focus()
      })
    },
    // 汽包确认框的确认,删除属性值
    deleteAttrValue(index) {
      this.attrInfo.attrValueList.splice(index, 1)
    },
    // 添加或者修改属性操作
    addOrUpdataAttr() {
      // 整理参数
      // 1.属性值为空不提交
      // 2.提交数据中不应该出现flag字段
      this.attrInfo.attrValueList = this.attrInfo.attrValueList.filter(item => {
        if (item.valueName !== '') {
          // 删除flag属性
          delete item.flag
          return true
        }
      })
      // 发送请求
      this.$API.attr
        .reqAddOrUpdateAttr(this.attrInfo)
        .then(res => {
          if (res.code === 200) {
            this.$message({ type: 'success', message: '保存成功' })
            // 再次获取平台属性展示
            this.getAttrList()

            this.isShowTable = true
          }
        })
        .catch(() => {
          this.$message({ type: 'error', message: '保存失败' })
        })
    }
  }
}
</script>

<style>
</style>
